package service

import (
	"context"
	"errors"
	"nearby/biz/common"
	"nearby/biz/domain/entity"
	"nearby/biz/model"
)

type CreateMomentService struct {
}

func (ss *CreateMomentService) checkParam(ctx context.Context, req *model.CreateMomentRequest) error {
	if req.Content.Text == "" && len(req.Content.ImageURLs) == 0 {
		return errors.New("发表内容不能为空")
	}
	return nil
}

func (ss *CreateMomentService) Execute(ctx context.Context, req *model.CreateMomentRequest) (resp *model.CreateMomentResponse, err error) {
	err = ss.checkParam(ctx, req)
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, err.Error(), err)
	}
	momentEntity, err := ss.ConstructMomentEntity(ctx, req)
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "发表动态失败...", err)
	}

	_ = momentEntity.SetMomentID()
	err = momentEntity.Persist(ctx)
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "创建动态失败...", err)
	}
	return &model.CreateMomentResponse{
		Meta:   common.MetaOk,
		Moment: momentEntity.ToVo(),
	}, nil
}

// ConstructMomentEntity 创建一个moment动态实体
func (ss *CreateMomentService) ConstructMomentEntity(ctx context.Context, req *model.CreateMomentRequest) (*entity.Moment, error) {
	user := common.GetUser(ctx)
	return &entity.Moment{
		User: entity.User{
			UserID:   user.UserID,
			Nickname: user.Nickname,
			HeadURL:  user.HeadURL,
		},
		Content: entity.PostContent{
			Text:      req.Content.Text,
			ImageUrls: req.Content.ImageURLs,
		},
		ViewCount: 1,
	}, nil
}
